package top.chukongxiang.dubboboot.simple.gateway.oauth2.provider.cas;

import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/31 9:52
 */
@Configuration
public class CasAuthenticationProviderConfigure {

    @Value("${cas.server.prefix-url}")
    private String casServerUrlPrefix;

    @Value("${cas.client.service-url}")
    public String defaultCasServiceUrl;

    private final CasAuthenticationUserDetailsServiceImpl casAuthenticationUserDetailsServiceImpl;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    public CasAuthenticationProviderConfigure(CasAuthenticationUserDetailsServiceImpl casAuthenticationUserDetailsServiceImpl) {
        this.casAuthenticationUserDetailsServiceImpl = casAuthenticationUserDetailsServiceImpl;
    }

    @Bean("pgtStorage")
    public ProxyGrantingTicketStorageImpl proxyGrantingTicketStorageImpl(){
        ProxyGrantingTicketStorageImpl proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();
        return proxyGrantingTicketStorage;
    }

    @Bean("casAuthenticationProvider")
    public CasAuthenticationProvider casAuthenticationProvider(){
        CasAuthenticationProvider authenticationProvider = new CasAuthenticationProvider();
        authenticationProvider.setKey("casProvider") ;
        // 此处不使用UserDetailService
        authenticationProvider.setAuthenticationUserDetailsService(casAuthenticationUserDetailsServiceImpl);
        authenticationProvider.setTicketValidator(ticketValidator());
        authenticationProvider.setServiceProperties(serviceProperties());
        return authenticationProvider;
    }

    @Bean
    public ServiceProperties serviceProperties(){
        ServiceProperties serviceProperties=new ServiceProperties();
        serviceProperties.setService(defaultCasServiceUrl);
        serviceProperties.setAuthenticateAllArtifacts(true);
        return serviceProperties;
    }

    /**
     * cas2.0协议验证规范，由server端决定
     * @return
     */
    @Bean
    public TicketValidator ticketValidator() {
        Cas20ProxyTicketValidator ticketValidator = new Cas20ProxyTicketValidator(casServerUrlPrefix);
        //允许所有代理回调链接
        ticketValidator.setAcceptAnyProxy(true);
        ticketValidator.setProxyGrantingTicketStorage(proxyGrantingTicketStorageImpl());
        return ticketValidator;
    }
}
